using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.Owin.Hosting;
using Microsoft.ApplicationServer.Caching;

namespace CNI.NRT.WebAPI
{
    public class WorkerRole : RoleEntryPoint
    {
        private IDisposable _app = null;
        public static DataCache myCache = null;

        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.TraceInformation("CNI.NRT.WebAPI entry point called", "Information");

            while (true)
            {
                Thread.Sleep(10000);
                Trace.TraceInformation("Working", "Information");
            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.UseNagleAlgorithm = false;
            ServicePointManager.Expect100Continue = false;
            ServicePointManager.SetTcpKeepAlive(false, 1, 1);
            ServicePointManager.DefaultConnectionLimit = 1000; 

            // OWIN startup code
            var endpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["http"];
            string baseUri = string.Format("{0}://{1}",
                endpoint.Protocol, endpoint.IPEndpoint);

            Trace.TraceInformation(String.Format("Starting OWIN at {0}", baseUri),
                "Information");

            _app = WebApp.Start<Startup>(new StartOptions(url: baseUri));

            // Cache startup code
            DataCacheFactoryConfiguration config = new DataCacheFactoryConfiguration("default");
            config.ChannelOpenTimeout = TimeSpan.FromSeconds(20);
            config.MaxConnectionsToServer = 100;
            config.RequestTimeout = TimeSpan.FromSeconds(20);

            DataCacheFactory myCacheFactory;
            DataCacheClientLogManager.ChangeLogLevel(TraceLevel.Warning);
            try
            {
                if (myCache == null)
                {
                    myCacheFactory = new DataCacheFactory(config);
                    myCache = myCacheFactory.GetDefaultCache();
                    myCache.CreateRegion("SENSORS");
                }
            }
            catch (DataCacheException dce)
            {
                Trace.TraceError(dce.ToString());
            }

            // start up the logger
            Logger.Start(RoleEnvironment.GetLocalResource("LogStore").RootPath);

            return base.OnStart();
        }

        public override void OnStop()
        {
            if (_app != null)
            {
                _app.Dispose();
            }
            base.OnStop();
        }
    }
}
